package service.impl.v2;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import dao.v2.ConfigVOMapper;
import model.WeixinOauth2TokenVO;
import net.sf.json.JSONObject;
import service.v2.CacheManagerService;
import service.v2.MemberChildService;
import service.v2.MemberService;
import service.v2.WeChatService;
import service.v2.WechatLoginService;
import util.WeixinUtil;

@Service
public class WechatLoginServiceImpl implements WechatLoginService{
	
	@Autowired
	private MemberChildService memberChildService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ConfigVOMapper configVOMapper;
	@Autowired
	private WeChatService wechatservice;
	
	public WeixinOauth2TokenVO getOpenId(String appId,String appSecret,String code) {
		WeixinOauth2TokenVO wat = new WeixinOauth2TokenVO();
	    // 拼接请求地址
		String bodyParams = "appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
		com.alibaba.fastjson.JSONObject jsonObject =JSON.parseObject(WeixinUtil.HttpRequest("https://api.weixin.qq.com/sns/oauth2/access_token",HttpMethod.GET,"",bodyParams));
        System.out.println(jsonObject);
	    if (null != jsonObject) {
            wat.setOpenId(jsonObject.getString("openid"));
            wat.setAccessToken(jsonObject.getString("access_token"));
            wat.setUnionId(jsonObject.getString("union_id"));
	    }
	    return wat;
	}
	public Map getUserinfo(String openid) {
		Map map = new HashMap();
		/*String access_token=null;
		// 拼接请求地址
	    String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
	    requestUrl = requestUrl.replace("ACCESS_TOKEN", access_token);
	    requestUrl = requestUrl.replace("OPENID", openid);
	    // 获取网页授权凭证
	    String c_result= CommonUtil.httpsRequest(requestUrl, "GET", null);
	    //	    下面要改
        JSONObject jsonObject =JSONObject.fromObject(c_result);
        if (null != jsonObject && jsonObject.get("errcode")!=null) {
    		access_token =wechatservice.getAccessToken();
        	requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
		    requestUrl = requestUrl.replace("ACCESS_TOKEN", access_token);
		    requestUrl = requestUrl.replace("OPENID", openid);
        	c_result= CommonUtil.httpsRequest(requestUrl, "GET", null);
        	jsonObject =JSONObject.fromObject(c_result);
        }
	    if (null != jsonObject && jsonObject.get("nickname")!=null) {
	    	map.put("nickname", jsonObject.getString("nickname"));
	    	if(jsonObject.getString("sex").equals("1")){
	    		map.put("sex", "M");
	    	}else{
	    		map.put("sex", "F");
	    	}
	    	map.put("headimgurl", jsonObject.getString("headimgurl"));
	    }*/
	    return map;
	}	

	public String getJsApiTicket() {
		String jsonStrTicket = null;
		
		String access_token = wechatservice.getAccessToken();
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		java.util.Date date=new java.util.Date();  
		String now=sdf.format(date); 
		String confValue = configVOMapper.loadConfig("JS_API_TICKET");
		JSONObject conf =JSONObject.fromObject(confValue);
	
		Date d1;
		Date d2;
		long seconds = 0 ;
		try {
			d1 = sdf.parse(now);
			d2 = sdf.parse(conf.getString("time"));  
			seconds = (d1.getTime() - d2.getTime())/1000;
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		//access token已经过时
	   if(seconds>7000){
		   jsonStrTicket = WeixinUtil.getJsApiTicket(access_token);
		   try {
				JSONObject updObj = new JSONObject();
				updObj.put("ticket", jsonStrTicket);
				if(seconds>7000){
					updObj.put("time", now);
				}else{
					updObj.put("time", conf.getString("time"));
				}
				configVOMapper.updConfValueByKey("JS_API_TICKET",updObj.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
	   }else{
		   jsonStrTicket = conf.getString("ticket");
	   }
		return jsonStrTicket;
	}

}
